package com.alasbusy.alasbusyapp.activity.fragment;

import android.content.Intent;
import android.os.Handler;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.alasbusy.alasbusyapp.R;
import com.alasbusy.alasbusyapp.activity.twoactivity.HtmlCssActivity;
import com.alasbusy.alasbusyapp.activity.twoactivity.ITNewsActivity;
import com.alasbusy.alasbusyapp.activity.twoactivity.NewsDetailActivity;
import com.alasbusy.alasbusyapp.adapter.HomeAdapter;
import com.alasbusy.alasbusyapp.adapter.HomeToolAdapter;
import com.alasbusy.alasbusyapp.base.BaseFragment;
import com.alasbusy.alasbusyapp.bean.HomeNewsKejiBean;
import com.alasbusy.alasbusyapp.bean.MaqureeBean;
import com.alasbusy.alasbusyapp.bean.hometool.HomeToolBean;
import com.alasbusy.alasbusyapp.dbutils.IntImp.AlasbusyIApi;
import com.alasbusy.alasbusyapp.dbutils.inter.HttpQuestResultListener;
import com.alasbusy.alasbusyapp.view.VerticalTextview;
import com.bumptech.glide.Glide;
import com.zhy.android.percent.support.PercentLinearLayout;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2018/5/14.
 */

public class HomeFragment extends BaseFragment implements View.OnClickListener, ViewPager.OnPageChangeListener, HttpQuestResultListener {


    private RecyclerView recyclerview;
    private SwipeRefreshLayout swiplayout;
    //private LinearLayoutManager linearLayoutManager;
    private HomeAdapter homeAdapter;
    public int Count = 0;
    public int nowpage = 0;

    private AppBarLayout mAppBarLayout;
    private CollapsingToolbarLayout mCollapsingToolbarLayout;
    private Toolbar toolbar;
    private ImageView home_back;
    private TextView home_name;
    private boolean userRegistionStatu;
    //private ImageView imgbackdrop;

    private List<ImageView> list_view = new ArrayList<>();
    // 底部小点图片
    private ImageView[] dots;
    private int currentIndex;
    private ViewPager viewpager;
    private LinearLayout pointgroup;

    public List<Integer> list = new ArrayList<>();
    public List<MaqureeBean> ImagePage = new ArrayList<>();
    private VerticalTextview maquree_txt;
    private ImageView home_notifa_img;
    private RecyclerView tool_recyclerview;
    private HomeToolAdapter homeToolAdapter;
    private int flage;
    // private TextView txt_name;

    @Override
    protected void initView(View view) {

        recyclerview = view.findViewById(R.id.recyclerview);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
        //GridLayoutManager gridLayoutManager = new GridLayoutManager(this.getContext(), 2);
        recyclerview.setLayoutManager(linearLayoutManager);
        recyclerview.setItemAnimator(new DefaultItemAnimator());
        homeAdapter = new HomeAdapter(getContext());
        recyclerview.setAdapter(homeAdapter);

        mAppBarLayout = (AppBarLayout) view.findViewById(R.id.appBarLayout);
        mCollapsingToolbarLayout = (CollapsingToolbarLayout) view.findViewById(R.id.CollapsingToolbarLayout);
        toolbar = (Toolbar) view.findViewById(R.id.toolbar);
        setInintView(toolbar);

        maquree_txt = (VerticalTextview) view.findViewById(R.id.maquree_txt);
        home_notifa_img = view.findViewById(R.id.home_notifa_img);

        // imgbackdrop = (ImageView) view.findViewById(R.id.imgbackdrop);

        tool_recyclerview = view.findViewById(R.id.tool_recyclerview);
        LinearLayoutManager toollinearlayout = new LinearLayoutManager(getContext());
        toollinearlayout.setOrientation(LinearLayoutManager.HORIZONTAL);
        tool_recyclerview.setLayoutManager(toollinearlayout);
        tool_recyclerview.setItemAnimator(new DefaultItemAnimator());
        homeToolAdapter = new HomeToolAdapter(getContext());
        tool_recyclerview.setAdapter(homeToolAdapter);

        view.findViewById(R.id.htmlcss_btn).setOnClickListener(this);
        view.findViewById(R.id.android_btn).setOnClickListener(this);
        view.findViewById(R.id.php_btn).setOnClickListener(this);
        view.findViewById(R.id.zixun_btn).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(getContext(), ITNewsActivity.class));
            }
        });
        view.findViewById(R.id.linux_btn).setOnClickListener(this);
        view.findViewById(R.id.webservice_btn).setOnClickListener(this);
        view.findViewById(R.id.book_btn).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //startActivity(new Intent(getContext(),BookActivity.class));
                //改为mysql优化
            }
        });
        view.findViewById(R.id.mysefl_btn).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //startActivity(new Intent(getContext(),OnTheWayActivity.class));
                //改为更多
            }
        });

        viewpager = (ViewPager) view.findViewById(R.id.viewpager);
        pointgroup = (LinearLayout) view.findViewById(R.id.pointgroup);
        //String[] titlePage = {"春江花月夜", "520表白日", "唉好忙", "经典美文任意看"};
    }

    private void setInintView(Toolbar toolbar) {
        home_back = (ImageView) toolbar.findViewById(R.id.home_back);
        home_back.setEnabled(false);
        home_name = (TextView) toolbar.findViewById(R.id.home_name);
    }

    ArrayList<MaqureeBean> mlist = new ArrayList<>();

    @Override
    protected void initData() {
        // onOwnerRefresh();
        ImagePage.clear();
        list_view.clear();
        setData(0);
        maquree_txt.setText(13, 0, getResources().getColor(R.color.c_FA85C7));//设置属性,具体跟踪源码
        maquree_txt.setTextStillTime(3000);//设置停留时长间隔
        maquree_txt.setAnimTime(300);//设置进入和退出的时间间隔
        //对单条文字的点击监听
        maquree_txt.setOnItemClickListener(new VerticalTextview.OnItemClickListener() {
            @Override
            public void onItemClick(String url) {
                // TO DO
                Intent intent = new Intent(getActivity(), NewsDetailActivity.class);
                intent.putExtra("url", url);
                startActivity(intent);
            }
        });

        List<HomeToolBean> mToolBean = new ArrayList<>();
        mToolBean.add(new HomeToolBean(R.drawable.xftp_tool, "xftp工具下载"));
        mToolBean.add(new HomeToolBean(R.drawable.git_tool, "Git工具下载"));
        mToolBean.add(new HomeToolBean(R.drawable.xshell_tool, "xshell工具下载"));
        homeToolAdapter.setList(mToolBean);
    }


    public void setData(int page) {
        //获取本地数据库里的数据
        /*guestRegistration = GuestRegistrationManager.getInstance().getGuestRegistration(page);
        if (guestRegistration != null && guestRegistration.size() > 0) {
            visitorReservationAdapter.setList(guestRegistration);
            fragment_visitor_reser.setAdapter(visitorReservationAdapter);
            visitorReservationAdapter.changeMoreStatus(SystemDeleteUserAdapter.LOADING_NO);
            fragment_visitor_reser.setVisibility(View.VISIBLE);
            no_data.setVisibility(View.GONE);
        }else {
            fragment_visitor_reser.setVisibility(View.GONE);
            no_data.setVisibility(View.VISIBLE);
        }*/
        AlasbusyIApi alasbusyIApi = AlasbusyIApi.getInstance(getContext());
        alasbusyIApi.setHttpQuestResultListener(this);
        alasbusyIApi.getTouTiaoList();
    }

    @Override
    protected void initListener() {
        mAppBarLayout.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
            @Override
            public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
                if (verticalOffset != 0) {
                    home_name.setVisibility(View.VISIBLE);
                    //mHandler.removeCallbacks(new ViewPageTask());
                    //mHandler.sendEmptyMessageDelayed(0,3000);
                } else {
                    home_name.setVisibility(View.INVISIBLE);
                    //mHandler.postDelayed(new ViewPageTask(),5000);
                }
            }
        });
    }

    @Override
    public int getLayout() {
        return R.layout.home_fragment_two;
    }

    @Override
    public void onClick(View view) {
        Intent intent = new Intent(getContext(), HtmlCssActivity.class);
        switch (view.getId()) {
            case R.id.htmlcss_btn:
                intent.putExtra("type", "html");
                break;
            case R.id.android_btn:
                intent.putExtra("type", "android");
                break;
            case R.id.php_btn:
                intent.putExtra("type", "php");
                break;
            case R.id.linux_btn:
                intent.putExtra("type", "linux");
                break;
            case R.id.webservice_btn:
                intent.putExtra("type", "web");
                break;
        }
        getActivity().startActivity(intent);
    }

    /*private void onOwnerRefresh() {
        swiplayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                homeAdapter.changeMoreStatus(HomeAdapter.LOADING_NO);
                swiplayout.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        // 下拉刷新  更新完后调用该方法结束刷新
                        if (nowpage == 0) {
                            setData(nowpage);
                        } else {
                            nowpage = nowpage - 1;
                            setData(nowpage);
                        }
                        homeAdapter.setList(list);
                        homeAdapter.notifyDataSetChanged();
                        swiplayout.setRefreshing(false);
                    }
                }, 2000);
            }
        });

        recyclerview.setOnScrollListener(new RecyclerView.OnScrollListener() {
            public int lastVisibleItem;

            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (newState == RecyclerView.SCROLL_STATE_IDLE && lastVisibleItem + 1 == homeAdapter.getItemCount()) {
                    homeAdapter.changeMoreStatus(HomeAdapter.LOADING_MORE);
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            //swipeLayout.setLoading(false);
                            // 上拉加载  更新完后调用该方法结束刷新
                            if (nowpage == Count) {
                                setData(Count);
                            } else {
                                nowpage = nowpage + 1;
                                setData(nowpage);
                            }
                            homeAdapter.setList(list);
                            recyclerview.smoothScrollToPosition(0);
                            homeAdapter.notifyDataSetChanged();
                        }
                    }, 2000);
                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                //visitorReservationAdapter.changeMoreStatus(SystemDeleteUserAdapter.PULLUP_LOAD_MORE);
                lastVisibleItem = linearLayoutManager.findLastVisibleItemPosition();
            }
        });
    }*/

    @Override
    public void onStart() {
        super.onStart();
    }

    @Override
    public void onResume() {
        maquree_txt.startAutoScroll();
        if (ImagePage.size() > 0) {
            mHandler.sendEmptyMessageDelayed(0, 3000);
        }
        /*home_notifa_img.setImageResource(R.drawable.home_notifacation_aima);
        AnimationDrawable animationDrawable1 = (AnimationDrawable) home_notifa_img.getDrawable();
        animationDrawable1.start();*/
        super.onResume();
    }

    @Override
    public void onPause() {
        //mHandler.removeCallbacks(new ViewPageTask());
        mHandler.removeCallbacksAndMessages(null);
        maquree_txt.stopAutoScroll();
        super.onPause();
    }

    @Override
    public void onStop() {
        //mHandler.removeCallbacks(new ViewPageTask());
        mHandler.removeCallbacksAndMessages(null);
        super.onStop();
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
    }

    @Override
    public void onPageSelected(int position) {
        setCurrentDot(position);
    }

    @Override
    public void onPageScrollStateChanged(int state) {
    }

    private void setCurrentDot(int position) {
        if (position < 0 || position > list_view.size() - 1
                || currentIndex == position) {
            return;
        }
        dots[position].setImageResource(R.drawable.circle_selector);
        //txt_name.setText(titlePage[position]);
        dots[currentIndex].setImageResource(R.drawable.circle_white);
        currentIndex = position;
    }

    @Override
    public void onError(Object e) {

    }

    @Override
    public void onSuccess(Object object) {
        if (object instanceof HomeNewsKejiBean) {
            HomeNewsKejiBean homeNewsKejiBean = (HomeNewsKejiBean) object;
            HomeNewsKejiBean.ResultBean result = homeNewsKejiBean.getResult();
            if (result != null) {
                List<HomeNewsKejiBean.ResultBean.DataBean> data = result.getData();
                if (data != null && data.size() > 0) {
                    homeAdapter.setList(data);
                    for (int i = 0; i < 5; i++) {
                        mlist.add(new MaqureeBean(data.get(i).getTitle(), R.mipmap.htmlcss_normal, data.get(i).getUrl()));
                        ImagePage.add(new MaqureeBean(data.get(i).getThumbnail_pic_s(), R.mipmap.htmlcss_normal, data.get(i).getUrl()));
                    }
                    maquree_txt.setTextList(mlist);
                    setViewPage();
                }
            }
        }
    }

    @Override
    public void onQuestErroCode(Object object) {

    }

    public void setViewPage() {
        PercentLinearLayout.LayoutParams layouts = new PercentLinearLayout.LayoutParams(
                new PercentLinearLayout.LayoutParams(PercentLinearLayout.LayoutParams.MATCH_PARENT, PercentLinearLayout.LayoutParams.MATCH_PARENT));
        if (ImagePage.size() > 0) {
            Log.i("KYCC", "imagapage  === " + ImagePage.size());
            for (int i = 0; i < ImagePage.size(); i++) {
                ImageView image = new ImageView(getContext());
                //image.setImageResource(ImagePage.get(i));
                image.setScaleType(ImageView.ScaleType.FIT_XY);
                image.setLayoutParams(layouts);
                Glide.with(getContext()).load(ImagePage.get(i).getTxt()).into(image);
                list_view.add(image);
            }
            dots = new ImageView[list_view.size()];
            for (int i = 0; i < dots.length; i++) {
                ImageView dot = new ImageView(getContext());
                dot.setImageResource(R.drawable.circle_white);
                dots[i] = dot;
                LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(new ViewGroup.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
                        LinearLayout.LayoutParams.WRAP_CONTENT));
                layoutParams.leftMargin = 5;
                layoutParams.rightMargin = 5;
                pointgroup.addView(dots[i], layoutParams);
            }
            currentIndex = 0;
            dots[currentIndex].setImageResource(R.drawable.circle_selector);// 设置为选中状态
            //txt_name.setText(titlePage[currentIndex]);
            viewpager.setOnPageChangeListener(this);

            ViewPagerAdapter adapter = new ViewPagerAdapter(list_view);
            viewpager.setAdapter(adapter);
            adapter.notifyDataSetChanged();
        }
    }

    private class ViewPagerAdapter extends PagerAdapter {
        private final List<ImageView> views;

        public ViewPagerAdapter(List<ImageView> list_view) {
            this.views = list_view;
        }

        @Override
        public int getCount() {
            return views.size();
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            //((ViewPager) container).removeView(views.get(position));
            container.removeView(views.get(position));
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            // 将当前视图添加到container中
            //((ViewPager) container).addView(views.get(position));
            View v = views.get(position);
            ViewGroup parent = (ViewGroup) v.getParent();
            if (parent != null) {
                parent.removeAllViews();
            }
            container.addView(views.get(position));
            views.get(position).setOnTouchListener(new NewTouchListener());
            // 设置当前视图的唯一标示Key
            return views.get(position);
        }
    }

    private class NewTouchListener implements View.OnTouchListener {

        @Override
        public boolean onTouch(View view, MotionEvent motionEvent) {
            switch (motionEvent.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    flage = 0;
                    mHandler.removeCallbacksAndMessages(null);
                    break;
                case MotionEvent.ACTION_CANCEL:
                    flage = 1;
                    mHandler.sendEmptyMessageDelayed(0, 3000);
                    break;
                case MotionEvent.ACTION_UP:
                    flage = 0;
                    int currentItem = viewpager.getCurrentItem();
                    Intent intent = new Intent(getActivity(), NewsDetailActivity.class);
                    intent.putExtra("url", ImagePage.get(currentItem).getId());
                    startActivity(intent);
                    mHandler.sendEmptyMessageDelayed(0, 3000);
                    break;
                default:
                    break;
            }
            return true;
        }
    }

    private int currentItem;

    /**
     * 图片轮播任务
     *
     * @author liuyazhuang
     */
    class ViewPageTask implements Runnable {

        @Override
        public void run() {
            mHandler.removeCallbacks(this);

            mHandler.sendEmptyMessage(0);
        }
    }

    /**
     * 接收子线程传递过来的数据
     */
    private Handler mHandler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            if (currentIndex == list_view.size() - 1) {
                currentItem = 0;
                viewpager.setCurrentItem(currentItem, false);
            } else {
                currentItem = (currentItem + 1) % list_view.size();
                viewpager.setCurrentItem(currentItem);
            }
            /*if (currentIndex == list_view.size() - 1) {
                viewpager.setCurrentItem(currentItem, false);
            } else {
                viewpager.setCurrentItem(currentItem);
            }*/
            setCurrentDot(currentItem);
            //mHandler.postDelayed(new ViewPageTask(), 5000);
            mHandler.sendEmptyMessageDelayed(0, 3000);
        }

        ;
    };
}
